package store

import (
	"simple-http-server/store"
	"sync"
)

type MemBookRepository struct {
	mu   sync.RWMutex
	data map[string]*store.Book
}

func (m *MemBookRepository) Create(book *store.Book) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.data[book.Name] = book
	return nil
}

func (m *MemBookRepository) Update(book *store.Book) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.data[book.Name] = book
	return nil
}

func (m *MemBookRepository) Get(name string) (*store.Book, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	return m.data[name], nil
}

func (m *MemBookRepository) GetAll() ([]*store.Book, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()
	books := make([]*store.Book, 0, len(m.data))
	for _, book := range m.data {
		books = append(books, book)
	}
	return books, nil
}

func (m *MemBookRepository) Delete(name string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	delete(m.data, name)
	return nil
}
